package com.zeus.service;

import com.zeus.mapper.CartInfoMapper;
import com.zeus.mapper.CartMapper;
import com.zeus.mapper.OrderDetailMapper;
import com.zeus.mapper.OrderMapper;
import com.zeus.pojo.CartInfo;
import com.zeus.pojo.Order;
import com.zeus.pojo.OrderDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 冯扬龙
 * @date 2021/4/20 20:45
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CartInfoMapper cartInfoMapper;
    @Autowired
    private CartMapper cartMapper;

    public List<Order> selectOrderList(int userId) {
        return orderMapper.selectOrderList(userId);
    }

    public int updateOrderState(int orderId) {
        return orderMapper.updateOrderState(orderId);
    }

    //点击结算和提交订单，产生的一系列操作
    public int addOrder(Order order) {
//        添加订单基本信息到order表，返回订单id
        orderMapper.addOrder(order);
//        添加订单信息详情到orderdetail表，查询订单详情表中的基本信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", order.getUserId());
        map.put("list", order.getOrderDetailList());
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailList(map);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("orderId", order.getOrderId());
        map2.put("list", orderDetailList);
        orderDetailMapper.addOrderDetailList(map2);
        return order.getOrderId();
    }

//同样也是点击结算提交订单发生的操作，只不过提交订单有两种方式，第一种是从商品页面直接下单，第二种是从购物车中直接点击提交下单，
// 这里的操作就是假如用户从购物车下单，那么下单以后我应该同时在购物车中删除刚才下单的商品，购物车中只留下没下单的商品

    public int addOrder(Order order, int cartId) {
//        添加订单基本信息到order表，返回订单id
        orderMapper.addOrder(order);
//        添加订单信息详情到orderdetail表，查询订单详情表中的基本信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", order.getUserId());
        map.put("list", order.getOrderDetailList());
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailList(map);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("orderId", order.getOrderId());
        map2.put("list", orderDetailList);
        orderDetailMapper.addOrderDetailList(map2);
        for(OrderDetail orderDetail : order.getOrderDetailList()){
            CartInfo cartInfo = new CartInfo();
            cartInfo.setSkuId(orderDetail.getSkuId());
            cartInfo.setCartId(cartId);
            cartInfoMapper.deleteGoodsFromCart(cartInfo);
            cartMapper.updateCart2(cartId);
        }
        return order.getOrderId();
    }

}
